# coding:utf-8
import requests
import json

from django.conf import settings
from django.http import HttpResponse, QueryDict, JsonResponse
from django.shortcuts import render
from django.views.generic import TemplateView, View, ListView
from dashboard.models import GraphiteKeys, GraphitGroupKey
from dashboard.forms.graphite import GraphiteKeysForm
from dashboard.server.product import Ztree

class GraphiteKeyView(ListView):
    form_class = GraphiteKeysForm
    paginate_by = 10
    model = GraphiteKeys
    context_object_name = "graphite_keys"
    template_name = "graphite/graphite_keys.html"

    def get_context_data(self, **kwargs):
        context = super(GraphiteKeyView, self).get_context_data(**kwargs)
        context['metrics'] = self.get_metrics()
        return context


    def get(self, request, *args, **kwargs):
        # graphite key管理
        return super(GraphiteKeyView, self).get(request, *args, **kwargs)


    def post(self, request, *args, **kwargs):
        form = self.form_class(request.POST)
        ret = {"status": 0}
        if form.is_valid():
            try:
                graphite_key = GraphiteKeys(**form.cleaned_data)
                graphite_key.save()
            except Exception as e:
                ret['status'] = 1
                ret['errmsg'] = e.args
        else:
            errmsg = form.errors.as_json()
            ret['status'] = 1
            ret['errmsg'] = errmsg

        return JsonResponse(ret, safe=True)

    def get_metrics(self):
        try:
            rep = requests.get(settings.GRAPHITE_METRICS)
            metrics = rep.json()
            metrics = list(set([ ".".join(metric.split('.')[1:]) for metric in metrics if not metric.startswith("carbon")]))
        except:
            metrics = []
        return metrics


class GraphiteGroupView(TemplateView):
    template_name = "graphite/graphite_group_keys.html"

    def get_context_data(self, **kwargs):
        context = super(GraphiteGroupView, self).get_context_data(**kwargs)
        context['ztree'] = json.dumps(Ztree().get())
        context['graphitekeys'] = GraphiteKeys.objects.all()
        return context


    def get(self, request, *args, **kwargs):
        return super(GraphiteGroupView, self).get(request, *args, **kwargs)


class GraphiteGroupKeysView(View):

    def put(self, request):
        """
        给product添加graphite key
        :param request:
        :return:
        """
        ret = {"status": 0}
        data = QueryDict(request.body).dict()
        try:
            GraphitGroupKey.objects.get(**data)
            ret['status'] = 1
            ret['errmsg'] = "该记录已存在"
        except GraphitGroupKey.DoesNotExist:
            GraphitGroupKey.objects.create(**data)
        return JsonResponse(ret)



    def delete(self, request):
        ret = {"status": 0}
        data = QueryDict(request.body).dict()
        print(data)
        try:
            GraphitGroupKey.objects.get(**data).delete()
        except GraphitGroupKey.DoesNotExist:
            ret['status'] = 1
            ret['errmsg'] = "该记录不存在"
        except Exception as e:
            ret['status'] = 1
            ret['errmsg'] = e.args
        return JsonResponse(ret)



    def get(self, request):
        ret = {"status":0}
        groupkey_id = request.GET.get("id", None)
        if id is None:
            ret['status'] = 1
            ret['errmsg'] = "非法操作"
            return JsonResponse(ret)
        try:
            graphite_groups = GraphitGroupKey.objects.filter(service_id__exact=groupkey_id)
            ret['data'] = list(GraphiteKeys.objects.filter(pk__in=[graphite_group.key_id for graphite_group in  graphite_groups]).values())
        except GraphitGroupKey.DoesNotExist:
            ret['data'] = []
        return JsonResponse(ret)
